define(["angularAMD","moment"], function (angularAMD,moment) {
    angularAMD.service('BadReasonService', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', "$calculater",
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater){
            var service = this;
            /**
             * options: {
             *      plot_no: 生產批編號,
             *      op_no: 作業站編號,
             *      abnormal_detail: 例外原因明細
             *      callback : function
             * }   
             **/
            service.init = function(options){ 
                if(!options){
                    options = {
                        plot_no: '',
                        op_no: '',
                        abnormal_detail: []
                    };
                }
                //取得例外原因類別
                function genBadType(badReasonList){
                    var badTypeList = [];
                    var badType = '';
                    badReasonList.forEach(function(badReason){
                        if(badType!=badReason.reason_type){
                            badTypeList.push({
                                reason_type: badReason.reason_type,
                                reason_sub_type: badReason.reason_sub_type
                            });
                            badType = badReason.reason_type;
                        }
                    });

                    return badTypeList;
                }
                
                function beforeConfirm(dialog, callback){
                    var total_surplus_qty = 0;//多餘數
                    var total_abnormal_qty = 0; //報廢
                    var total_lack_qty = 0;//短少

                    dialog.badReasonInfo.forEach(function(info){
                        if(info.abnormal_type == '11'){
                            total_surplus_qty = $calculater.decimalAdd(total_surplus_qty, (+info.defect_qty));
                        } else if(info.abnormal_type == '12'){
                            total_lack_qty = $calculater.decimalAdd(total_lack_qty, (+info.defect_qty));
                        } else {
                            total_abnormal_qty =  $calculater.decimalAdd(total_abnormal_qty, (+info.defect_qty));
                        }
                    });
                    dialog.total_surplus_qty = total_surplus_qty;
                    dialog.total_abnormal_qty = total_abnormal_qty; 
                    dialog.total_lack_qty = total_lack_qty;

                    if (callback)
                        callback();
                }

                function qcReasonBasisInfoGet(callback){
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_WIP.qc_reason_basis_info_get',
                        content : {
                            op_no : options.op_no
                        },
                        success : function(data, response){
                            if (data.Result != 'fail') {
                                if (callback)
                                    callback(data.qc_reason_basis);
                            } else {
                                $rootScope.showAlert(response.Message);
                            }
                        }
                    });
                }

                function beforeOpenDialog(callback){
                    qcReasonBasisInfoGet(function(reasonList){
                        if (callback)
                            callback(reasonList);
                    });
                }

                //開窗
                function openDialog(reasonList){
                    $mdDialog.dialog(
                        'module/moduleB/program/B02/B0217/BadReason.tmp.html',
                        function(dialog){
                            return {
                                css_url:'module/moduleB/program/B02/B0217/BadReason.css',
                                parent: options.parent,
                                plot_no: options.plot_no || '',
                                badTypeList: genBadType(reasonList), //0: 報廢, 11: 多餘 , 12: 短少
                                badCodeList: reasonList,
                                tmpBadReason: {},
                                tmpBadType: '',
                                tmpBadTypeName: '',
                                tmpAbnormal_qty: '',
                                badReasonInfo: options.abnormal_detail || [],
                                total_surplus_qty: 0, //總多餘數
                                total_abnormal_qty: 0, //總報廢數
                                total_lack_qty: 0, //總短少數
                                beforeShown: function(){
                                    if(dialog.parent == 'B0217'){
                                        dialog.badTypeList = $filter('filter')(dialog.badTypeList, {reason_type: '0'}, true);
                                        if(dialog.badTypeList.length > 0){
                                            dialog.tmpBadType = dialog.badTypeList[0].reason_type;
                                            dialog.tmpBadTypeName = dialog.badTypeList[0].reason_sub_type;
                                        }
                                    }
                                },
                                back: function () {
                                    dialog.hide();
                                },
                                loadBadTypeList: function(){
                                    $rootScope.showSelect({
                                        label: 'reason_sub_type',
                                        code: 'reason_type',
                                        selectCode: dialog.tmpBadType,
                                        list: dialog.badTypeList,
                                        confirm: function (item, radioDialog) {
                                            radioDialog.hide();
                                            dialog.tmpBadType = item.reason_type;
                                            dialog.tmpBadTypeName = item.reason_sub_type;
                                            dialog.tmpBadReason = {};
                                        }
                                    });
                                },
                                loadBadReasonList: function(){
                                    if(dialog.tmpBadType != ''){
                                        $rootScope.showQueryList({
                                            key:'reason_no',
                                            title:$filter('translate')('common.queryList.badReason_select'),
                                            header : [
                                                {label: $filter('translate')('common.queryList.reason_c'), code:'reason_no'},
                                                {label: $filter('translate')('common.queryList.reason_n'), code:'reason_name'}
                                            ],
                                            query: function(conditions, feedback){
                                                feedback($filter('filter')(dialog.badCodeList, {reason_type:dialog.tmpBadType}));
                                            },
                                            confirm: function(selectItem, radioDialog){
                                                radioDialog.hide();
                                                dialog.tmpBadReason = selectItem;
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0217.msg.bad_type_empty'));
                                    }
                                },
                                //新增不良原因
                                addBadReason: function(){
                                    if(!dialog.tmpBadReason.reason_name){
                                        $rootScope.showAlert($filter('translate')('B0217.badReason.msg.bad_reason_empty'),function(){
                                            if(dialog.parent != 'B0217'){
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                            }
                                            dialog.tmpBadReason = {};
                                            dialog.tmpAbnormal_qty = '';
                                        });
                                    }else{
                                        if (dialog.tmpAbnormal_qty > 0) {
                                            //20220728 modify by wangzy for 0111274: [SMES]生產批現況有狀態12資料，但於例外處理卻找不到[宏毅]
                                            //判断是否已添加此原因，已添加则不再重复添加
                                            if (dialog.badReasonInfo.filter(item => { return item.abnormal_no == dialog.tmpBadReason.reason_no && item.plot_no == dialog.plot_no }).length == 0) {
                                                dialog.badReasonInfo.push({
                                                    plot_no: dialog.plot_no,
                                                    abnormal_type: dialog.tmpBadReason.reason_type,
                                                    abnormal_type_name: dialog.tmpBadReason.reason_sub_type,
                                                    abnormal_no: dialog.tmpBadReason.reason_no,
                                                    abnormal_name: dialog.tmpBadReason.reason_name,
                                                    defect_qty: dialog.tmpAbnormal_qty,
                                                });
                                            }
                                            if(dialog.parent != 'B0217'){
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                            }
                                            dialog.tmpBadReason = {};
                                            dialog.tmpAbnormal_qty = '';
                                            //console.log(dialog.badReasonInfo);
                                        }else{
                                            $rootScope.showAlert($filter('translate')('B0217.badReason.msg.qty_empty'),function(){
                                                dialog.tmpAbnormal_qty = '';
                                            });
                                        }
                                    }
                                },
                                //刪除不良原因
                                removeBadReason : function(item){
                                    dialog.badReasonInfo.splice(dialog.badReasonInfo.indexOf(item), 1);
                                },
                                //不良原因-確定
                                confirm : function(){
                                    beforeConfirm(dialog, function(){
                                        if (options.callback){
                                            options.callback(dialog);
                                        } else {
                                            dialog.hide();
                                        }
                                    });
                                }
                            };
                        }
                    );
                }

                beforeOpenDialog(function(reasonList){
                    openDialog(reasonList);
                });
            };
        }]);
});
